package solver;
import ilog.cplex.*;
import ilog.concert.*;
//二次规划: 目标函数为二次型
/*
 *  min (1/2)xPx+qx+r
 *  s.t. -1<=x_i<=1 i=1,2,3
 *  P={{13,12,-2},{12,17,6},{-2,6,12}};
 *  q={-22,14.5,13}, r=1;
 */
public class qp1 {

	public static void main(String[] args) {
		try {
			IloCplex cplex=new IloCplex();
			double[][] P={{13,12,-2},{12,17,6},{-2,6,12}};
			double[] q= {-22,-14.5,13};
			double r=1;
			double[] lb= {-1,-1,-1};
			double[] ub= {1,1,1};
			IloNumVar[] x=cplex.numVarArray(3,lb,ub);
			int n=P.length;
			IloNumExpr expr1=cplex.numExpr();
			for(int j=0;j<n;j++)
			{	
				for(int i=0;i<n;i++)
				{
					expr1=cplex.sum(expr1,cplex.prod(x[i],P[i][j],x[j]));
				}
			}
			IloNumExpr expr2=cplex.scalProd(q, x);
			IloNumExpr expr3=cplex.sum(cplex.sum(cplex.prod(0.5, expr1),expr2),r);
			IloObjective obj=cplex.addMinimize(expr3);

			cplex.setParam(IloCplex.Param.OptimalityTarget,IloCplex.OptimalityTarget.FirstOrder);//设定求解策略
			 
	         if ( cplex.solve() ) {
	            System.out.println("Solution status="+cplex.getStatus());
	            System.out.println("obj value="+cplex.getObjective());
	            for(int i=0;i<n;i++)
	            {
	            	System.out.println("x["+(i+1)+"]="+cplex.getValue(x[i]));
	            }
	         }
	         cplex.end();
			
			
			
			
			
			
		}catch(IloException e)
		{
			System.err.println("Concert exception "+e+"caught");
		}

	}

}
